package com.llh.cheap.controllers;

import top.moirae.repository.PaginationForm;
import top.moirae.rest.AbstractRestResponse;
import top.moirae.rest.ControllerSupport;
import top.moirae.security.HWSession;
import top.moirae.security.models.Session;
import top.moirae.security.forms.IdsForm;
import top.moirae.rest.ErrorRestResponse;
import org.springframework.validation.BindingResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.llh.cheap.forms.CheapUserForm;
import com.llh.cheap.facades.CheapUserFacade;
import jakarta.validation.Valid;

/**
 * @author lilinhan
 **/
@RestController
@RequestMapping("/cheap-user")
public class CheapUserController extends ControllerSupport {
    private final CheapUserFacade cheapUserFacade;

    @Autowired
    public CheapUserController(CheapUserFacade cheapUserFacade) {
        this.cheapUserFacade = cheapUserFacade;
    }

    @PostMapping
    public AbstractRestResponse create(@HWSession Session session, @RequestBody @Valid CheapUserForm.Create form, BindingResult result) {
        if (result.hasErrors()) {
            return ErrorRestResponse.apply(BINDING_ERROR.apply(result));
        }
        return AbstractRestResponse.apply(cheapUserFacade.create(session, form));
    }

    @GetMapping("/{id}")
    public AbstractRestResponse get(@PathVariable long id) {
        return AbstractRestResponse.apply(cheapUserFacade.get(id));
    }

    @PutMapping("/{id}")
    public AbstractRestResponse update(@HWSession Session session, @PathVariable Long id, @RequestBody CheapUserForm.Update form, BindingResult result) {
        if (result.hasErrors()) {
            return ErrorRestResponse.apply(BINDING_ERROR.apply(result));
        }
        return AbstractRestResponse.apply(cheapUserFacade.update(session, id, form));
    }

    @DeleteMapping
    public AbstractRestResponse delete(@HWSession Session session, @RequestBody @Valid IdsForm idsForm) {
        return AbstractRestResponse.apply(cheapUserFacade.delete(session, idsForm));
    }

    @GetMapping("/list")
    public AbstractRestResponse list(@HWSession Session session, @Valid CheapUserForm.Search form, BindingResult result) {
        if (result.hasErrors()) {
            return ErrorRestResponse.apply(BINDING_ERROR.apply(result));
        }
        return AbstractRestResponse.apply(cheapUserFacade.list(session, form));
    }

    @GetMapping
    public AbstractRestResponse pageList(@HWSession Session session, CheapUserForm.Search form, @Valid PaginationForm paginationForm, BindingResult result) {
        if (result.hasErrors()) {
            return ErrorRestResponse.apply(BINDING_ERROR.apply(result));
        }
        return AbstractRestResponse.apply(cheapUserFacade.pageList(session, form, paginationForm));
    }
}

